//
//  WeathView.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/2/27.
//  Copyright © 2016年 game. All rights reserved.
//

#import "WeathView.h"

#import "TYWaveProgressView.h"
#import "ForeInfoModel.h"

#define IMAGE_X                arc4random()%(int)SCREEN_WIDTH
#define IMAGE_ALPHA            ((float)(arc4random()%10))/10
#define IMAGE_WIDTH            arc4random()%20 + 10
#define PLUS_HEIGHT            screen_height/25
#define rainCount 220

@interface WeathView ()

@property (nonatomic,strong) UILabel *timelab;
@property (nonatomic, weak) TYWaveProgressView *waveProgressView;

@property (weak, nonatomic) IBOutlet UIView *bacview;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backHight;

@property (nonatomic, assign) NSInteger raincount;

@property (nonatomic,strong) UIImageView *sunImage;

@property (nonatomic,strong) NSMutableArray *snowAry;

@property (nonatomic,strong) UIImageView *SundyIMg;

@property (nonatomic,assign) int snowI;

@end

@implementation WeathView

-(instancetype)initWithFrame:(CGRect)frame{

    if (self = [super initWithFrame:frame]) {
        
        self.raincount = 0;
        
    }
    return self;
}

-(void)setDatamodel:(WeathForecastModel *)Datamodel{

    _Datamodel = Datamodel;
    
 
    
    [self.fatherCtl StopWeatherViewTime];

    if ([_model.weather isEqualToString:@"晴"]) {
        [self SunAction];
    }
    
    if ([_model.weather rangeOfString:@"雨"].length!=0) {
        [self RainAction];
    }
    
    
    if ([_model.weather rangeOfString:@"雪"].length!=0) {
        [self SnowAction];
    }
    

}

-(void)setModel:(WeathForecastModel *)model{

    _model = model;
    
    
    
    _waveProgressView.numberLabel.text = _model.score;
    _waveProgressView.explainLabel.text = _model.score_msg;
    _waveProgressView.unitLabel.text = @"分";
    _waveProgressView.percent = [_model.score integerValue]/100.0;
    

        [_waveProgressView startWave];
  
    


    [self.bacview.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    for (int i=0; i<_model.info.count; i++) {
        
        CGFloat yd = 10;
        
        CGFloat hh = 25;
        
        CGFloat yy =  (yd+hh)*i;
        UILabel *lab = [[UILabel alloc]init];
        
        lab.frame = CGRectMake(12, yy, SCREEN_WIDTH, hh);
        
        ForeInfoModel *forecemodel = _model.info[i];
        

        lab.text = [NSString stringWithFormat:@"%@：%@",forecemodel.name,forecemodel.info];
        
        lab.textColor = [UIColor whiteColor];
    
        [self.bacview addSubview:lab];
    }
    


    [self.fatherCtl StopWeatherViewTime];
    
    if ([_model.weather isEqualToString:@"晴"]) {
         [self SunAction];
    }
    
    if ([_model.weather rangeOfString:@"雨"].length!=0) {
        [self RainAction];
    }
    
    
    if ([_model.weather rangeOfString:@"雪"].length!=0) {
        [self SnowAction];
    }

    
    UIColor *color1;
    UIColor *color2;
    
    if ([_model.score_name isEqualToString:@"适宜"]) {
        color1 = RGBA(0, 191, 255, 1);
        color2 = RGBA(0, 191, 255, 0.6);
    }
    
    if ([_model.score_name isEqualToString:@"很适宜"]) {
        color1 = [UIColor colorWithRed:55.f/255.f green:178.f/255.f blue:16.f/255.f alpha:1];
        color2 =[UIColor colorWithRed:55.f/255.f green:178.f/255.f blue:16.f/255.f alpha:0.6];
    }
    
    if ([_model.score_name isEqualToString:@"不适宜"]) {
        color1 =   [UIColor colorWithRed:240/255.0f green:133/255.0f blue:25/255.0f alpha:1.0];
        color2 =  [UIColor colorWithRed:240/255.0f green:133/255.0f blue:25/255.0f alpha:0.6];
    }
    
    if ([_model.score_name isEqualToString:@"极不适宜"]) {
        
        color1 = RGBA(255, 0, 0, 1);
        color2 = RGBA(255, 0, 0,0.6);
    }

    _waveProgressView.waterWaveView.firstWaveColor = color1;
    _waveProgressView.waterWaveView.secondWaveColor = color2;
}

- (void)addWaveProgressView
{
    
    UIImage *bacImage = [UIImage imageNamed:@"ball~iphone"];
    
    TYWaveProgressView *waveProgressView = [[TYWaveProgressView alloc]initWithFrame:CGRectMake(20, 30, bacImage.size.width,bacImage.size.height)];
    
    waveProgressView.backgroundImageView.image = bacImage;
    
    waveProgressView.waveViewMargin = UIEdgeInsetsMake(1, 1, 1, 1);
    
    waveProgressView.numberLabel.font = font(SCREEN_WIDTH*0.10);
    waveProgressView.numberLabel.textColor = [UIColor whiteColor];
    waveProgressView.numberLabel.centerX = waveProgressView.centerX-20;
    
    waveProgressView.unitLabel.font = font(SCREEN_WIDTH*0.048);
    waveProgressView.unitLabel.textColor = [UIColor whiteColor];
    
    waveProgressView.explainLabel.font = font(SCREEN_WIDTH*0.045);
    waveProgressView.explainLabel.textColor = [UIColor whiteColor];
    
    [self addSubview:waveProgressView];
    _waveProgressView = waveProgressView;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(Tap)];

    [_waveProgressView addGestureRecognizer:tap];
}



-(void)Tap{
    
    [_waveProgressView startWave];
}
-(void)awakeFromNib{
    
  [self addWaveProgressView];
    self.backHight.constant = SCREEN_HEIGHT*1/3+20;
    self.bacview.backgroundColor = [UIColor clearColor];
    
    self.backgroundColor = [UIColor clearColor];
}

-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];

   
}

/**
 *  下雨
 */
-(void)RainAction{
    
    
    // 获得队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        // 创建一个定时器(dispatch_source_t本质还是个OC对象)
        
        if (self.timer==nil) {
            
            self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        }
        
        dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
        uint64_t interval = (uint64_t)(0.1 * NSEC_PER_SEC);
        dispatch_source_set_timer(self.timer, start, interval, 0);
        
        // 设置回调
        dispatch_source_set_event_handler(self.timer, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self animation];
                [self animation];
                [self animation];
                [self animation];
                [self animation];
            });
        });
        
        // 启动定时器
        
        dispatch_resume(self.timer);
    });
}


-(void)animation{
    

    
    if (self.raincount <=rainCount) {
        @synchronized(self) {
        UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"rain1~iphone"]];
        imageView.tag = 100000000000+self.raincount;
        self.raincount++;
        int x = arc4random() % (int)(screen_width+80);
        
        imageView.frame = CGRectMake(x, -50, 8, 40);

        [self.fatherCtl.view addSubview:imageView];
        
        [UIView animateWithDuration:2 animations:^{
            
            imageView.frame = CGRectMake(x-80, screen_height, 8, 40);
        } completion:^(BOOL finished) {
            imageView.frame = CGRectMake(x, -50, 8, 40);
        }];
        }
    }else
    {
        @synchronized(self) {
        UIImageView * imageView = (UIImageView *)[self.fatherCtl.view viewWithTag:100000000000+self.raincount%rainCount-1];
        
        self.raincount++;
        
        CGRect frame = imageView.frame;

        [UIView animateWithDuration:2 animations:^{
            
            imageView.frame = CGRectMake(frame.origin.x-130, screen_height, 8, 40);
            
        } completion:^(BOOL finished) {
            
            imageView.frame = frame;
        }];
        }
    }
}


/**
 *  下雪
 */
-(void)SnowAction{
    
    _snowAry = [[NSMutableArray alloc] init];
    for (int i = 0; i < 20; ++ i) {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"snow"]];
        
        float x = IMAGE_WIDTH;
        
        imageView.frame = CGRectMake(IMAGE_X, -30, x, x);
        imageView.alpha = IMAGE_ALPHA;
        [self.fatherCtl.view addSubview:imageView];
        [_snowAry addObject:imageView];
    }
    
    [_snowTimer invalidate];
   
    _snowTimer =[NSTimer scheduledTimerWithTimeInterval:.3 target:self selector:@selector(makeSnow) userInfo:nil repeats:YES];
}

//static int i = 0;
- (void)makeSnow
{
    self.snowI = self.snowI  + 1;
    if ([_snowAry count] > 0) {
        
        UIImageView *imageView = [_snowAry objectAtIndex:0];
        imageView.tag = self.snowI +1000000;
        
        [_snowAry removeObjectAtIndex:0];
        [self snowFall:imageView];
    }
    
}

- (void)snowFall:(UIImageView *)aImageView
{
    
    [UIView beginAnimations:[NSString stringWithFormat:@"%li",(long)aImageView.tag] context:nil];
    [UIView setAnimationDuration:6];
    [UIView setAnimationDelegate:self];
    aImageView.frame = CGRectMake(aImageView.frame.origin.x, screen_height, aImageView.frame.size.width, aImageView.frame.size.height);
    
    [UIView commitAnimations];
}


- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{

    UIImageView *imageView = (UIImageView *)[self.fatherCtl.view viewWithTag:([animationID intValue])];
    float x = IMAGE_WIDTH;
    imageView.frame = CGRectMake(IMAGE_X, -30, x, x);
    [_snowAry addObject:imageView];
 
}


/**
 *  太阳旋转
 */
-(void)SunAction{
    
    [self.SundyIMg removeFromSuperview];
    
    [self.sunImage removeFromSuperview];
    
    self.SundyIMg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"sun~iphone"]];
    
    self.SundyIMg.tag = 10000000;
    
    self.SundyIMg.frame = CGRectMake(SCREEN_WIDTH-self.SundyIMg.image.size.width+20,80,self.SundyIMg.image.size.width, self.SundyIMg.image.size.height);
    [self.fatherCtl.view addSubview:self.SundyIMg];
    
    self.sunImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"sunshine~iphone"]];
    [self.fatherCtl.view addSubview:self.sunImage];
    self.sunImage.frame = CGRectMake(0, 0, self.sunImage.image.size.width-20, self.sunImage.image.size.height);
    
    self.sunImage.tag = 10000000000;
    self.sunImage.centerX = self.SundyIMg.centerX;
    self.sunImage.centerY = self.SundyIMg.centerY+5;
    
    
    [self ApalwhithTime:5.0f];

    
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: -M_PI * 2.0 ];
    rotationAnimation.duration = 20;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 10000;
    
    [self.sunImage.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    
}


-(void)ApalwhithTime:(CGFloat )time{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.sunImage.alpha = 0;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           
            self.sunImage.alpha = 1;
            
            [self ApalwhithTime:time];
            
        });
    });
}

/**
 *  闪电
 */
-(void)ShandianAction{
    [self.sunImage removeFromSuperview];
    
    self.sunImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"top_bg_woman"]];
    
    [self.fatherCtl.view addSubview:self.sunImage];
}

-(void)StopAllNil{
    [self.sunImage removeFromSuperview];
    [self.SundyIMg removeFromSuperview];
    
    self.snowI = 0;
 
    UIView *view = [self.fatherCtl.view.superview viewWithTag:10000000000];
    [view removeFromSuperview];
    
    UIView *view2 = [self.fatherCtl.view.superview viewWithTag:10000000];
    [view2 removeFromSuperview];
    
    
    
    self.timer = nil ;
    
    self.raincount = 0;
    
    [self.snowTimer invalidate];
    self.snowTimer = nil;
    self.raincount = 0;
}

@end
